package com.musollo.mp3tools.categorizers;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.musollo.domain.MP3;
import com.musollo.mp3tools.AbstractMP3Categorizer;

/**
 * This categorizer categorizes MP3 files in the following folders.
 * 
 * Artistfolder -> Albumfolder -> mp3 file.
 * 
 * MP3 file name is renamed to "<tracknumber> - <song title>.mp3"
 * 
 * @author paw.janssen
 * 
 */
public class SimpleCategorizer extends AbstractMP3Categorizer {
	private static final Logger LOGGER = Logger.getLogger(SimpleCategorizer.class);

	/**
	 * {@inheritDoc}
	 * 
	 * @throws IOException
	 */
	@Override
	public void categorizeMP3(final MP3 mp3) throws IOException {
		if (this.getTargetDir() == null) {
			throw new IllegalStateException("Cannot categorize an MP3 when target directory is null");
		}
		if (mp3 == null) {
			throw new IllegalArgumentException("Cannot categorize null MP3");
		}

		String categorizedPathString = this.getTargetDir().getAbsolutePath() + File.separatorChar;
		categorizedPathString += mp3.getArtist() + File.separatorChar;
		categorizedPathString += mp3.getAlbum() + File.separatorChar;

		File categorizedPath = new File(categorizedPathString);

		LOGGER.debug("Categorizing mp3 into \"" + categorizedPathString + "\"");

		if (!categorizedPath.exists()) {
			FileUtils.forceMkdir(categorizedPath);
		}

		String categorizedFileString = mp3.getAlbumTrackNumber() + " - " + mp3.getTitle() + ".mp3";
		File categorizedFile = new File(categorizedPath, categorizedFileString);

		if (categorizedFile.exists()) {
			throw new IOException("Categorized file: \"" + categorizedFile.getAbsolutePath() + "\" already exists.");
		}

		LOGGER.debug("MP3 categorized to \"" + categorizedFileString + "\"");
		FileUtils.moveFile(mp3.getMp3File(), categorizedFile);
	}
}
